<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.3/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"iyue.top","root":"/","images":"/images","scheme":"Muse","version":"8.3.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>
<meta name="description" content="js变量的类型我们知道js变量有两种类型  基本类型值，指简单的数据段，对于undefined、null、boolean、number、string这5种简单数据类型可以直接操作保存在变量中的实际值，也就是按值访问。 引用类型值，指那些可能由多个值构成的对象，只能操作对象的引用而不是实际的对象，所以要得到引用类型这种值只能按引用访问。  变量的存放方式有如下代码段（赋值基本类型） 12var a&#x3D;">
<meta property="og:type" content="article">
<meta property="og:title" content="js变量在内存的存放解惑">
<meta property="og:url" content="http://iyue.top/2018/08/24/js%E5%8F%98%E9%87%8F%E5%9C%A8%E5%86%85%E5%AD%98%E7%9A%84%E5%AD%98%E6%94%BE%E8%A7%A3%E6%83%91/index.html">
<meta property="og:site_name" content="山外小楼">
<meta property="og:description" content="js变量的类型我们知道js变量有两种类型  基本类型值，指简单的数据段，对于undefined、null、boolean、number、string这5种简单数据类型可以直接操作保存在变量中的实际值，也就是按值访问。 引用类型值，指那些可能由多个值构成的对象，只能操作对象的引用而不是实际的对象，所以要得到引用类型这种值只能按引用访问。  变量的存放方式有如下代码段（赋值基本类型） 12var a&#x3D;">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2018-08-24T11:56:56.000Z">
<meta property="article:modified_time" content="2021-04-27T08:41:57.637Z">
<meta property="article:author" content="萌新">
<meta property="article:tag" content="值类型">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://iyue.top/2018/08/24/js%E5%8F%98%E9%87%8F%E5%9C%A8%E5%86%85%E5%AD%98%E7%9A%84%E5%AD%98%E6%94%BE%E8%A7%A3%E6%83%91/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>js变量在内存的存放解惑 | 山外小楼</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">山外小楼</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">前端攻略</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#js%E5%8F%98%E9%87%8F%E7%9A%84%E7%B1%BB%E5%9E%8B"><span class="nav-number">1.</span> <span class="nav-text">js变量的类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%98%E9%87%8F%E7%9A%84%E5%AD%98%E6%94%BE%E6%96%B9%E5%BC%8F"><span class="nav-number">2.</span> <span class="nav-text">变量的存放方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E4%BC%A0%E5%8F%82%E6%98%AF%E6%8C%89%E5%80%BC%E4%BC%A0%E9%80%92%E8%BF%98%E6%98%AF%E5%BC%95%E7%94%A8%E4%BC%A0%E9%80%92"><span class="nav-number">3.</span> <span class="nav-text">函数传参是按值传递还是引用传递</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="nav-number">4.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">萌新</p>
  <div class="site-description" itemprop="description">我是萌新</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">21</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://iyue.top/2018/08/24/js%E5%8F%98%E9%87%8F%E5%9C%A8%E5%86%85%E5%AD%98%E7%9A%84%E5%AD%98%E6%94%BE%E8%A7%A3%E6%83%91/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="萌新">
      <meta itemprop="description" content="我是萌新">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="山外小楼">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          js变量在内存的存放解惑
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2018-08-24 19:56:56" itemprop="dateCreated datePublished" datetime="2018-08-24T19:56:56+08:00">2018-08-24</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-04-27 16:41:57" itemprop="dateModified" datetime="2021-04-27T16:41:57+08:00">2021-04-27</time>
      </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="js变量的类型"><a href="#js变量的类型" class="headerlink" title="js变量的类型"></a>js变量的类型</h2><p>我们知道js变量有两种类型</p>
<ul>
<li>基本类型值，指简单的数据段，对于undefined、null、boolean、number、string这5种简单数据类型可以直接操作保存在变量中的实际值，也就是按值访问。</li>
<li>引用类型值，指那些可能由多个值构成的对象，只能操作对象的引用而不是实际的对象，所以要得到引用类型这种值只能按引用访问。</li>
</ul>
<h2 id="变量的存放方式"><a href="#变量的存放方式" class="headerlink" title="变量的存放方式"></a>变量的存放方式</h2><p>有如下代码段（赋值基本类型）</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a=<span class="number">1</span>;</span><br><span class="line"><span class="keyword">var</span> b=<span class="number">1</span>;</span><br></pre></td></tr></table></figure>
<p>上述代码定义了两个变量，定义<code>a=1</code>在栈内存开辟一块空间存放<code>1</code>这个值，同理定义<code>b=1</code>也开辟一块内存存放<code>1</code>这个值；<br>当修改变量的值的时候，比如重新赋值<code>a=3</code>，那么就会重新开辟一块内存，将<code>3</code>存入后，把<code>a</code>指向<code>3</code>所在的内存位置；</p>
<blockquote>
<p>有个问题还没考证，就是不同的变量定义的值一样的时候，是不是指向的是同一块内存。在python中可以通过id来访问存放位置的id，在值（基本类型）较小的时候，就是指向同一块内存</p>
</blockquote>
<p>有如下代码段（赋值引用类型）</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> c=&#123;<span class="attr">name</span>:<span class="string">&#x27;阿Q&#x27;</span>&#125;;</span><br><span class="line"><span class="keyword">var</span> d=&#123;<span class="attr">name</span>:<span class="string">&#x27;阿Q&#x27;</span>&#125;;</span><br></pre></td></tr></table></figure>
<p>上述代码定义了两个变量，定义<code>c</code>的时候在栈内存开辟一块空间存放一个内存地址，这个内存地址指向堆内存中放<code>&#123;name:&#39;阿Q&#39;&#125;</code>这个对象的内存；<code>d</code>同样如此，而且两个对象是毫无关系的，他们的内存地址是不一样的。<br>当修改变量的值的时候，如<code>c=&#123;name:&#39;老王&#39;&#125;</code>，这种情况就和基本类型一样，属于重新赋值，就会将对象<code>&#123;name:&#39;老王&#39;&#125;</code>存到堆内存中，将对象的地址存到栈内存中，c指向这个内存；<br>当修改变量，如<code>c.name=&#39;老张&#39;</code>，这种情况可以看作给对象做一个修正或者扩展，不属于重新赋值，虽然结果是修改了对象，但并没有改动对象所在的位置，即<code>c</code>指向的栈内存里存放的对象的地址并没有变；<br>当然如果如下定义</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> c=d=&#123;<span class="attr">name</span>:<span class="string">&#x27;阿Q&#x27;</span>&#125;;</span><br><span class="line"><span class="comment">// 或者</span></span><br><span class="line"><span class="keyword">var</span> a=b=<span class="number">1</span>;</span><br></pre></td></tr></table></figure>
<p>这样的连等赋值，有另外的说法，之后专写一篇关于连等赋值的问题。  </p>
<h2 id="函数传参是按值传递还是引用传递"><a href="#函数传参是按值传递还是引用传递" class="headerlink" title="函数传参是按值传递还是引用传递"></a>函数传参是按值传递还是引用传递</h2><p>对于这块内容，网上很多博文说法很多，还有说共享传递啥的，在此我们不对这些字面进行讨论，我们就解释下本质到底是怎么个情况。<br>比如有如下代码</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">    x = <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line">foo(a);</span><br><span class="line"><span class="built_in">console</span>.log(a); <span class="comment">// 仍为1, 未受x = 2赋值所影响</span></span><br></pre></td></tr></table></figure>
<p>这个就无需多解释了，x作为一个形参，只在函数内部生效，而且当a当作参数传给x的时候，其实就是复制了一份a指向的栈内存中存放的值，所以a和x就是毫无关系了<br>如果a为一个引用类型，如下代码</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;<span class="attr">x</span> : <span class="number">1</span>&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">o</span>) </span>&#123;</span><br><span class="line">    o.x = <span class="number">3</span>;</span><br><span class="line">&#125;</span><br><span class="line">foo(obj);</span><br><span class="line"><span class="built_in">console</span>.log(obj.x); <span class="comment">// 3, 被修改了!</span></span><br></pre></td></tr></table></figure>
<p>此处也一样，x作为一个形参，当obj当作参数传给o的时候，其实是复制了一份obj指向的栈内存中存放的对象的地址，所以obj和o在栈内存中是不一样的，但在栈内存中存的东西是一样的，就是对象<code>&#123;x : 1&#125;</code>所在的地址；<br>所以当修改o的时候，自然obj也就被修改了<br>还有人提出以下代码  </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = &#123;<span class="attr">name</span>:<span class="string">&#x27;foo&#x27;</span>&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">o</span>)</span>&#123;</span><br><span class="line">   o = &#123;<span class="attr">name</span>:<span class="string">&#x27;bar&#x27;</span>&#125;;  </span><br><span class="line">&#125;</span><br><span class="line">test(foo);</span><br><span class="line"><span class="built_in">console</span>.log(foo.name); <span class="comment">// foo，未被修改；</span></span><br></pre></td></tr></table></figure>
<p>这个结果是没问题的，但这就是上文提到的对对象的修改的方式的问题，是直接赋值去修改变量，还是去修改对象的属性；<br>上述代码foo当作参数传给o，同样将对象所在地址赋值一份给了形参o，但函数中o的赋值操作，使形参o完全指向了另外一个对象的内存地址，这个操作，并不影响实参foo在内存中存放的地址，及地址所指向的对象；  </p>
<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h2><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_34377264/article/details/72782668">JS中函数的参数是按值传递还是按引用传递</a><br><a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000010953733">JavaScript参数按值传递的理解</a><br><a target="_blank" rel="noopener" href="https://www.cnblogs.com/mcray/p/7002089.html">JS进阶系列之内存空间</a></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E5%80%BC%E7%B1%BB%E5%9E%8B/" rel="tag"># 值类型</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2018/08/22/js%E4%B8%AD%E7%9A%84%E4%BD%9C%E7%94%A8%E5%9F%9F/" rel="prev" title="你不知道的JavaScript-第一部分">
                  <i class="fa fa-chevron-left"></i> 你不知道的JavaScript-第一部分
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2018/09/05/post%E8%AF%B7%E6%B1%82%E7%9A%84%E6%8F%90%E4%BA%A4%E6%95%B0%E6%8D%AE%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F/" rel="next" title="post请求的提交数据的几种方式">
                  post请求的提交数据的几种方式 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">萌新</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  






  





</body>
</html>
